//
//  CYSigmentView.swift
//  segemNav
//
//  Created by cy on 2017/1/27.
//  Copyright © 2017年 m2micro. All rights reserved.
//



import UIKit
import Foundation

protocol CYSigmentViewDelegate:NSObjectProtocol {
    /**
     *  点击横向点击事件
     *
     *  @param sengment sengment对象
     *  @param index    点击的索引
     */
    func segment(sengment:CYSigmentView,didSelectColumnIndex index:NSInteger)
}

class CYSigmentView: UIView {
    
   dynamic var titleNomalColor:UIColor?
   dynamic var titleSelectColor :UIColor?
   dynamic var titleFont :UIFont?
   dynamic var defaultIndex = 1
    var text :NSString?
    weak  var delegate : CYSigmentViewDelegate?
    var menuHeight = CGFloat(0)
    var btnArrays : [UIButton]?
    var titleBtn : UIButton?
    var backScrollView : UIScrollView?
    var bottomLine : UIView?
    var btnWidth = CGFloat(0)
     var titleArray : [String]?
    
    override init(frame:CGRect){
        super.init(frame: frame)
        menuHeight=self.height
        btnArrays=[UIButton]()
        titleFont=UIFont.systemFont(ofSize: 15)
        titleNomalColor=UIColor.init(red: 80, green: 80, blue: 80, alpha: 1.0)
        titleSelectColor=UIColor.orange
        backScrollView=UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.width, height: self.height))
        backScrollView?.showsHorizontalScrollIndicator=false
        backScrollView?.backgroundColor=UIColor.lightGray
        addSubview(backScrollView!)
       

    }
    
    convenience init(frame: CGRect,titleArr:[String]) {
        self.init(frame:frame)
        
        self.titleArray =  titleArr;
        if (titleArray?.count)!<6 {
            btnWidth=self.width/CGFloat((titleArray?.count)!)
            }else{
             btnWidth=self.width/5
            }

        
//        let line = UIView.init(frame: CGRect.init(x: 0, y: menuHeight-0.5, width: btnWidth*CGFloat((titleArray?.count)!), height: 0.5))
//        line.backgroundColor=UIColor.orange
//        backScrollView?.addSubview(line)
        
        bottomLine = UIView.init(frame: CGRect.init(x:(btnWidth-50)/2+CGFloat(defaultIndex-1)*btnWidth, y: menuHeight-2, width: 50, height: 2))
        bottomLine?.backgroundColor=UIColor.orange
        backScrollView?.addSubview(bottomLine!)
    
        backScrollView?.contentSize=CGSize.init(width: btnWidth*CGFloat((titleArray?.count)!), height: menuHeight)
        for i in 0..<(titleArray?.count)! {
            let btn = UIButton.init(type: .custom)
            btn.frame=CGRect.init(x: btnWidth*CGFloat(i), y: 0, width: btnWidth, height: menuHeight-2)
            btn.tag=i+1
            btn.setTitle(titleArray?[i], for: .normal)
            btn.setTitleColor(titleNomalColor, for: .normal)
            btn.setTitleColor(titleSelectColor, for: .selected)
            btn.addTarget(self, action: #selector(btnTitleClick(sender:)), for: .touchUpInside)
           
            btn.titleLabel?.font=titleFont
            backScrollView?.addSubview(btn)
            btnArrays?.append(btn)
            if i==defaultIndex-1 {
                titleBtn=btn
                btn.isSelected=true
            }
        }
         registerForKVO()
    }
    

    fileprivate func registerForKVO(){
        for i in 0..<observablrKeypaths().count {
            addObserver(self, forKeyPath: observablrKeypaths()[i], options: .new, context: nil)
        }
    
    }
    
    fileprivate func observablrKeypaths() ->[String]{
       return ["titleNomalColor","titleSelectColor","titleFont","defaultIndex"]
    
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            updateUIForKeypath(keypath: keyPath!)
    }
    
    
    fileprivate func updateUIForKeypath(keypath:String){
        if keypath == "titleNomalColor" {
            updateViewUI({ (btn)->Void in
                btn?.setTitleColor(self.titleNomalColor, for: .normal)
            })
        }else if keypath == "titleSelectColor"{
            updateViewUI({ (btn)->Void in
                btn?.setTitleColor(self.titleSelectColor, for: .selected)
            })
        }else if keypath == "titleFont"{
            updateViewUI({ (btn)->Void in
                btn?.titleLabel?.font=self.titleFont
            })

        }else if keypath == "defaultIndex"{
            updateViewUI({ (btn)->Void in
                if (btn?.tag)!-1 == self.defaultIndex-1{
                self.titleBtn=btn
                    btn?.isSelected=true
                }else{
                    btn?.isSelected=false
                }
            })
            
        }
        setNeedsLayout()
        setNeedsDisplay()
    }
    
    fileprivate func updateViewUI(_ complated:(_ btn:UIButton?) -> Void){
        for i in 0..<(btnArrays?.count)! {
            let btn = btnArrays?[i]
                btn?.setTitleColor(self.titleNomalColor, for: .normal)
            btn?.setTitleColor(self.titleSelectColor, for: .selected)
            btn?.titleLabel?.font=self.titleFont
            complated(btn)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //title点击事件
    @objc func btnTitleClick(sender:UIButton){
        if delegate != nil && ((delegate?.segment(sengment: didSelectColumnIndex: )) != nil) {
            delegate?.segment(sengment: self, didSelectColumnIndex: sender.tag)
        }
        if sender.tag==defaultIndex {
            return
        }else{
            titleBtn?.isSelected=false
            sender.isSelected=true
            titleBtn=sender
            defaultIndex=sender.tag

        }
        //计算偏移量
        var offsetX = sender.x-2*btnWidth
        if offsetX<0 {
            offsetX=0
        }
        let maxOffsetX = (backScrollView?.contentSize.width)!-(backScrollView?.width)!
        if offsetX>maxOffsetX {
            offsetX=maxOffsetX
        }
        
        UIView.animate(withDuration: 0.2, animations: { 
            self.backScrollView?.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
            self.bottomLine?.frame=CGRect.init(x: sender.x+(sender.width-50)/2, y: sender.height-2, width: 50, height: 2)
        }) { (finished) in
            
        }
    
    }
    
    func collectionScrollPositon(index:Int) {
        let button = viewWithTag(index)
        btnTitleClick(sender: button as! UIButton)
        
    }

}
